package com.ebocy.hammer.core.socket.codecFilter;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.log.LoggerConstants.CuteLoggerType;
import com.ebocy.hammer.core.message.MessageConstants;

public class AsRequestDecoder extends CumulativeProtocolDecoder {
	protected static Logger logger = EbocyLogManager.getSystemLogger();
	
	private static int maxPackLength = 4096;

	/**
	 * 这个方法的返回值是重点： 1、当内容刚好时，返回false，告知父类接收下一批内容
	 * 2、内容不够时需要下一批发过来的内容，此时返回false，这样父类 CumulativeProtocolDecoder
	 * 会将内容放进IoSession中，等下次来数据后就自动拼装再交给本类的doDecode
	 * 3、当内容多时，返回true，因为需要再将本批数据进行读取，父类会将剩余的数据再次推送本 类的doDecode
	 */
	@Override
	public boolean doDecode(IoSession session, IoBuffer buffer, ProtocolDecoderOutput out) throws Exception {
		Logger originalRecord2 = EbocyLogManager.getLogger(CuteLoggerType.ORIGINAL2, Level.INFO);
//		if (buffer.remaining() < 4) return false;//如果消息头都不够就返回
//		buffer.mark();//标记
//		int mesID = buffer.getUnsignedShort();//读取消息ID
//		int mesLength = buffer.getUnsignedShort();//读取消息长度
//		if (buffer.remaining() < mesLength){//如果消息长度不够
//			buffer.reset();//回到标记位置，相当于没读过长度和ID
//			return false;//返回
//		}
//		IoBuffer tmp = buffer.duplicate();
//		tmp.reset();//回到初始位置，ID和长度也要还原
//		output.write(tmp);//数据够了继续往下级传递
//		return true;
		
		
		if (buffer.remaining() < MessageConstants.MSG_HEADER_LEN)
			return false;
		
		buffer.mark();
		int length = buffer.getInt();
		if (length < 0 || length > maxPackLength) {
			Logger originalRecord3 = EbocyLogManager.getLogger(CuteLoggerType.ORIGINAL3, Level.INFO);
			originalRecord3.info(buffer.getHexDump());
//			buffer.clear();
//			return false;
		}
		
		if (length >= MessageConstants.MSG_HEADER_LEN + MessageConstants.MSG_CODE_LEN
				&& length - MessageConstants.MSG_HEADER_LEN <= buffer.remaining()) {
			int oldLimit = buffer.limit();
			buffer.limit(buffer.position() + length - 4);
			int bodyLen = buffer.remaining();
			byte[] body = new byte[bodyLen];
			buffer.get(body);
			buffer.limit(oldLimit);
			out.write(IoBuffer.wrap(body));
			return true;
		} else {
			buffer.reset();
			return false;
		}
	}
	
	

}
